package cn.devhost;

import cn.hutool.http.HttpUtil;
import cn.lingyangwl.framework.core.response.Resp;
import cn.lingyangwl.framework.core.response.RetOps;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

/**
 * @author shenguangyang
 */
@Component
public class AppRunner implements ApplicationRunner {
    @Resource
    private ClientProperties clientProperties;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        ServerInfo serverInfo = HostUtils.getCurrentServerInfo();
        String ip = serverInfo.getIp();
        String subIp = ip.substring(0, serverInfo.getIp().lastIndexOf(".") + 1);

        Map<String, List<ClientProperties.MatchServer>> matchServerMap = clientProperties.getMatchServer().stream()
                .collect(Collectors.groupingBy(e -> e.getHostName().toLowerCase(Locale.ROOT)));
        int count = 255;
        ExecutorService executorService = Executors.newCachedThreadPool();
        CountDownLatch countDownLatch = new CountDownLatch(254);
        while (count-- > 1) {
            int finalCount = count;
            executorService.execute(()->{
                AtomicBoolean rst = new AtomicBoolean(false);
                String requestIp = subIp + finalCount;
                String requestUrl = "http://" + requestIp + ":" + clientProperties.getServerPort();
                try {
                    String body = HttpUtil.get(requestUrl, 100);
                    Resp<ServerInfo> resp = JSONObject.parseObject(body, new TypeReference<Resp<ServerInfo>>() {});
                    String hostname = resp.getData().getHostname();
                    if (RetOps.of(resp).isSuccess() && matchServerMap.containsKey(hostname.toLowerCase(Locale.ROOT))) {
                        synchronized (this) {
                            System.out.println("============================ find ip: " + requestIp + ", hostname: " + hostname);
                            List<ClientProperties.MatchServer> matchServers = matchServerMap.get(hostname.toLowerCase(Locale.ROOT));
                            matchServers.stream().flatMap(e -> e.getDomains().stream()).forEach(e -> {
                                try {
                                    rst.set(HostUtils.append(requestIp, e));
                                } catch (IOException ex) {
                                    throw new RuntimeException(ex);
                                }
                            });
                            System.out.println("isSuccess: " + rst);
                            HostUtils.read().forEach(System.out::println);
                        }
                    }
                } catch (Exception e) {

                } finally {
                    countDownLatch.countDown();
                }
            });
        }
        countDownLatch.await();
        System.out.println("================== run end!!");
        executorService.shutdown();
    }
}
